from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql
from pymysql.cursors import DictCursor

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'learning_management',
    'port': 3306,
    'charset': 'utf8mb4'
}

# 连接数据库的工具函数
def get_db_connection():
    conn = pymysql.connect(
        **DB_CONFIG,
        cursorclass=DictCursor
    )
    return conn

# 注册API接口
@app.route('/api/register', methods=['POST'])
def register():
    conn = None
    try:
        data = request.get_json()
        username = data.get('username', '').strip()
        account = data.get('account', '').strip()
        password = data.get('password', '').strip()
        
        # 数据验证
        if not username or not account or not password:
            return jsonify({
                'success': False,
                'message': '用户名、账号和密码不能为空'
            }), 400
        
        conn = get_db_connection()
        with conn.cursor() as cursor:
            # 检查账号是否已存在
            cursor.execute("SELECT * FROM users WHERE account = %s", (account,))
            if cursor.fetchone():
                return jsonify({
                    'success': False,
                    'message': '账号已存在'
                }), 400
            
            # 插入新用户
            cursor.execute(
                "INSERT INTO users (username, account, password) VALUES (%s, %s, %s)",
                (username, account, password)
            )
            conn.commit()
            
            return jsonify({
                'success': True,
                'message': '注册成功'
            }), 200
            
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'注册失败：{str(e)}'
        }), 500
    finally:
        if conn:
            conn.close()

# 登录API接口
@app.route('/api/login', methods=['POST'])
def login():
    conn = None
    try:
        data = request.get_json()
        account = data.get('account', '').strip()
        password = data.get('password', '').strip()
        
        # 数据验证
        if not account or not password:
            return jsonify({
                'success': False,
                'message': '账号和密码不能为空'
            }), 400
        
        conn = get_db_connection()
        with conn.cursor() as cursor:
            # 验证账号密码
            cursor.execute("SELECT * FROM users WHERE account = %s AND password = %s", 
                         (account, password))
            user = cursor.fetchone()
            
            if user:
                return jsonify({
                    'success': True,
                    'message': '登录成功',
                    'data': {
                        'id': user['id'],
                        'username': user['username'],
                        'account': user['account']
                    }
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': '账号或密码错误'
                }), 400
                
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'登录失败：{str(e)}'
        }), 500
    finally:
        if conn:
            conn.close()

# 获取用户信息API接口
@app.route('/api/user/<int:user_id>', methods=['GET'])
def get_user_info(user_id):
    conn = None
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            cursor.execute("SELECT id, username, account FROM users WHERE id = %s", (user_id,))
            user = cursor.fetchone()
            
            if user:
                return jsonify({
                    'success': True,
                    'data': user
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': '用户不存在'
                }), 404
                
    except Exception as e:
        print('login error:', e)  # 加这一行
        return jsonify({
            'success': False,
            'message': f'获取用户信息失败：{str(e)}'
        }), 500
    finally:
        if conn:
            conn.close()

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)